// import { Post, SyncPost } from '/@/api/linxyun/base/index.ts'
import IFileClient from './file_client_interface.js';
import { httpReqeustApi } from '/@/api/linxyun/base';

const httpReqeust = httpReqeustApi();

export default class FileClient_Eslithe extends IFileClient {
	constructor(fileConfig) {
		super(fileConfig);
	}
	getFileID(fileUrl) {
		if (!fileUrl) {
			console.error('[Error][File]get file id fail, url is empty');
			return null;
		}
		let pos = fileUrl.indexOf('fileUrl=');
		if (pos < 0) {
			return fileUrl;
		}
		return fileUrl.substr(pos + 8);
	}
	getFileFullUrl(fileID) {
		if (!fileID) {
			return null;
		}
		if (fileID.indexOf('http') === 0) {
			return fileID;
		}

		if (this._fileConfig === null || !this._fileConfig.setting.imgUrl) {
			console.log('[getFileFullUrl]Failed to upload file, no file config info.');
			return null;
		}
		// return this._fileConfig.setting.imgUrl + fileID
		return fileID;
	}

	// 返回文件ID
	async uploadContent(fileName, content) {
		console.log('[Debug][File][eslithe]upload file, file: ', fileName, content);
		const formData = new FormData();
		formData.append('file', content, fileName);
		let res = await httpReqeust.SyncPost(this._fileConfig.setting.uploadUrl, null, formData);
		console.log('yyyyyyyyyyyyyyyyyy, res: ', res);
		if (!res || !res.data || res.code !== '0000') {
			console.error('[Error][File][uploadFile][eslithe]Upload fail, res: ', res);
			return null;
		}
		//return res.data.FileID
		let fullUrl = await this.getFileFullUrl(res.data);
		console.log('[Debug][File][eslithe]upload file complete, file: ', fileName, ', url: ', fullUrl);
		return fullUrl;
	}
	async deleteFile(url) {
		console.log('[Debug][File]delete file, url: ', url);
		if (!this._fileConfig) {
			console.error('[Error][File][deleteFile][eslithe]No file config info.');
			return false;
		}

		if (!this._fileConfig.setting.deleteUrl || this._fileConfig.setting.deleteUrl === null) {
			console.error('[Error][File][deleteFile][eslithe]No deleteUrl.');
			return false;
		}

		let fileID = this.getFileID(url);
		if (!fileID || fileID === '') {
			console.error('[Error][File]delete file, file is empty');
			return false;
		}
		await httpReqeust.Post(this._fileConfig.setting.deleteUrl, { FileID: fileID, fileUrl: fileID });

		return true;
	}
}
